//
//  SearchViewController.m
//  Pink
//
//  Created by ZhongDaYunKe on 15/12/16.
//  Copyright © 2015年 ycy. All rights reserved.
//

#import "SearchViewController.h"
#import "AppDelegate.h"

@interface SearchViewController ()<UIAlertViewDelegate>
@property (nonatomic,strong)NSMutableArray *dataSource;

@end

@implementation SearchViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    self.navigationItem.leftBarButtonItem = nil;
    _dataSource = [[NSMutableArray alloc] init];
    self.view.backgroundColor = [UIColor whiteColor];
    [self initSubviews];
}


-(void)viewWillAppear:(BOOL)animated
{
    self.navigationController.navigationBarHidden = YES;
}

-(void)viewWillDisappear:(BOOL)animated
{
    self.navigationController.navigationBarHidden = NO;
}

- (void)initSubviews
{
    
    
    
    _searchBar = [[UISearchBar alloc] initWithFrame:CGRectMake(0, 20, self.view.size.width, 44)];
    _searchBar.delegate = self;
    _searchBar.placeholder = @"输入内容";
    _searchBar.barTintColor = [UIColor colorFromHexString:@"2DBBA6"];
     _searchBar.showsCancelButton = YES;
//    _searchBar.backgroundColor = [UIColor clearColor];
    _searchBar.returnKeyType = UIReturnKeySearch;
    [self.view addSubview:_searchBar];
    [_searchBar becomeFirstResponder];
    
    UIView *backVIew = [[UIView alloc] initWithFrame:CGRectMake(0, 0, self.view.size.width, 21)];
    backVIew.backgroundColor = [UIColor colorFromHexString:@"2DBBA6"];
    [self.view addSubview:backVIew];
    

    
    _tableView  = [[UITableView alloc] initWithFrame:CGRectMake(0, 64, self.view.size.width, self.view.size.height) style:UITableViewStylePlain];
    _tableView.delegate = self;
     _tableView.dataSource = self;
    _tableView.tableFooterView = [[UIView alloc] init];
    [self.view addSubview:_tableView];
    
}

-(void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    [_searchBar resignFirstResponder];
}

-(void)searchBarSearchButtonClicked:(UISearchBar *)searchBar
{
    WS(weakself)
    ALERTMESSAGE(@"搜索中...")
    AVQuery *searchQuery = [AVQuery queryWithClassName:@"Topic"];
    searchQuery.limit = 1000;
    searchQuery.cachePolicy = kAVCachePolicyCacheElseNetwork;
    searchQuery.maxCacheAge = 60 * 24;
    [searchQuery whereKey:@"name" equalTo:searchBar.text];
    [searchQuery findObjectsInBackgroundWithBlock:^(NSArray *objects, NSError *error) {
        if (objects) {
            ALERTDISMISS
            NSLog(@"%@",objects);
            if (objects.count == 0) {
                
                UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"还没有这个版块,是否创建？" message:@"写下该版块的相关描述:" delegate:weakself cancelButtonTitle:@"取消" otherButtonTitles:@"确定", nil];
                alert.alertViewStyle = UIAlertViewStylePlainTextInput;
                [alert show];
            }else{
                [_dataSource addObjectsFromArray:objects];
                [_tableView reloadData];
            }
        }else{
            ALERTFAILED(error.description)
        }
    }];
    
}


-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if (buttonIndex == 1) {
        NSLog(@"%@",[alertView textFieldAtIndex:0].text);
        WS(weakself)
        ALERTMESSAGE(@"创建中...")
        Topic *topic= [[Topic alloc] init];
        topic.name = self.searchBar.text;
        topic.descriptions = [alertView textFieldAtIndex:0].text;
        [AVClient saveObjectWithClassName:@"Topic" model:topic success:^(BOOL succeeded, NSError *error) {
            if (succeeded) {
                [AppDelegate shareAppdelegate].selectTopic = topic;
                ALERTSUCCESS(@"创建成功")
                dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                    [weakself.navigationController popViewControllerAnimated:NO];
                });
            }else{
                ALERTFAILED(error.description);
            }
        }];
    }
}


-(void)searchBarCancelButtonClicked:(UISearchBar *)searchBar
{
    [self.navigationController popViewControllerAnimated:NO];
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return _dataSource.count;
}


-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *cellIdentifier = @"cell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
    if (cell == nil) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:cellIdentifier];
        
    }
    
    Topic *topic = [Topic modelWithDictionary:[AVClient RealDictionaryForObject:_dataSource[indexPath.row]]];
    
    cell.textLabel.text = topic.name;
    cell.detailTextLabel.text = topic.descriptions;
    
    return cell;
}


-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:NO];
    
    
     Topic *topic = [Topic modelWithDictionary:[AVClient RealDictionaryForObject:_dataSource[indexPath.row]]];
    [AppDelegate shareAppdelegate].selectTopic = topic;
    
    [self.navigationController popViewControllerAnimated:NO];
    
    
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
